﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RN.ERP.Web.ModelService;
using Newtonsoft.Json;
using Fly.Common.Linq;
using Fly.Common.WorkFlow;
using Telerik.Web.UI;
using Telerik.Web.UI.Skins;

namespace RN.ERP.Web.Enterprise
{
    public partial class EnterpriseSelect : BasePage
    {
        protected string AreaCode
        {
            get
            {
                return UserInfo.CurrentArea;
            }
        }


        private EnterpriseService.EnterpriseServiceClient enterpriseServiceClient = new EnterpriseService.EnterpriseServiceClient();
        private BasicService.BasicServiceClient basicServiceClient = new BasicService.BasicServiceClient();
        private PersonService.PersonServiceClient personServiceClient = new PersonService.PersonServiceClient();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetParams(); 
            }
        }

        private void GetParams()
        {
            hdnClassID.Value = Request["classId"];
            Guid empGuid = Guid.Empty;
            Guid gid = Guid.Empty;
            if (!string.IsNullOrEmpty(Request.QueryString["empGuid"]))
            {
                if (Guid.TryParse(Request.QueryString["empGuid"], out empGuid))
                {
                    hdEmpGuid.Value = empGuid.ToString();
                }
            }
            if (!string.IsNullOrEmpty(Request.QueryString["gid"]))
            {
                if (Guid.TryParse(Request.QueryString["gid"], out gid))
                {
                    hdGid.Value = gid.ToString();
                    hdStatus.Value = "1";
                    var relation = JsonConvert.DeserializeObject<tb_User_Relation>(personServiceClient.GetUserRelationInfo(hdGid.Value, UserInfo.CurrentArea));
                    if (relation != null && relation.EntityGuid != null)
                    {
                        hdEntityGuid.Value = relation.EntityGuid.ToString();
                    }
                }
            }
            if (!string.IsNullOrEmpty(Request.QueryString["Flag"]))
            {
                hdFlag.Value = Request.QueryString["Flag"];
            }
            
        }

        /// <summary>
        /// 客户端grid刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            if (e.Argument == "Rebind")
            {
                ListCorps.MasterTableView.SortExpressions.Clear();
                ListCorps.MasterTableView.GroupByExpressions.Clear();
                ListCorps.Rebind();
            }
        }

        protected void ListCorps_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            string corpName = txtCorpName.Text.Trim();
            if (!string.IsNullOrEmpty(hdGid.Value) ||!string.IsNullOrEmpty(corpName))
            {
                string ClassId = Request.QueryString["classId"];
                var queryCondition = GetCondition();
                var corp = enterpriseServiceClient.GetCompanyAllInfo(queryCondition, ListCorps.PageSize, ListCorps.CurrentPageIndex + 1, "02");
                var corpInfo = JsonConvert.DeserializeObject<IList<CompanyInfo>>(corp);
                int cnt = enterpriseServiceClient.GetCompanyCount(queryCondition, "02");
                ListCorps.AllowCustomPaging = true;
                ListCorps.VirtualItemCount = cnt;
                ListCorps.DataSource = corpInfo;
                if (!string.IsNullOrEmpty(hdGid.Value))
                {
                    var initialCondition = GetInitialCondition();
                    var initialCorp = enterpriseServiceClient.GetCompanyAllInfo(initialCondition, ListCorps.PageSize, ListCorps.CurrentPageIndex + 1, UserInfo.CurrentArea);
                    var initialCorpinfo = JsonConvert.DeserializeObject<IList<CompanyInfo>>(initialCorp);
                    if (ListCorps.CurrentPageIndex == 0)
                    {
                        var retcorp = initialCorpinfo.FirstOrDefault();
                        if (retcorp != null)
                        {
                            if (!corpInfo.Any(o => o.CorpUserGuid == retcorp.CorpUserGuid))
                            {
                                ListCorps.DataSource = initialCorpinfo.Union(corpInfo);
                                ListCorps.PageSize = 11;
                            }
                        }
                    }
                }
            }
        }

        protected string GetCorpClassKind(string type)
        {
            string output = string.Empty;
            if (!String.IsNullOrEmpty(type))
            {
                Dictionary<string, string> CorpTypeDic = JsonConvert.DeserializeObject<Dictionary<string, string>>
                    (Application[ApplicationConstant.APPLICATION_CORPUSERTYPE].ToString());
                try
                {
                    output = CorpTypeDic[type];
                }
                catch
                {
                    output = "";
                }
            }
            return output;
        }

        private string GetCondition()
        {
            List<QueryCompanyInfoCondition> queryCompanyInfoList = new List<QueryCompanyInfoCondition>();
            QueryCompanyInfoCondition queryCompanyInfoCondition = new QueryCompanyInfoCondition();
            string classId = Request.QueryString["classId"];
            string corpName = txtCorpName.Text.Trim();
            int clsId = -1;
            if (!string.IsNullOrEmpty(classId) && int.TryParse(classId, out clsId))
            {
                queryCompanyInfoCondition.classID = new ParameterValue<int?>() { O = OptEnum.Equal, V = clsId };
            }
            if (!string.IsNullOrEmpty(corpName))
            {
                queryCompanyInfoCondition.CorpName = new ParameterValue<string>() { O = OptEnum.Like, V = corpName };
            }
            ////解决烟台地区查看外地企业需求,这里说是地区号换字段了，但是前台获取不到变更后的字段，暂时还取以前的账号 2014-01-02 毛凯
            if (UserInfo.AreaCode.Length >= 4)
            {
                queryCompanyInfoCondition.AreaCode = new ParameterValue<string>() { O = OptEnum.StartWith, V = UserInfo.AreaCode };
            }
            queryCompanyInfoList.Add(queryCompanyInfoCondition);
            return JsonConvert.SerializeObject(queryCompanyInfoList);
        }

        private string GetInitialCondition()
        {
            List<QueryCompanyInfoCondition> queryCompanyInfoList = new List<QueryCompanyInfoCondition>();
            QueryCompanyInfoCondition queryCompanyInfoCondition = new QueryCompanyInfoCondition();
            string classId = Request.QueryString["classId"];
            string corpName = txtCorpName.Text.Trim();
            int clsId = -1;
            if (!string.IsNullOrEmpty(classId) && int.TryParse(classId, out clsId))
            {
                queryCompanyInfoCondition.classID = new ParameterValue<int?>() { O = OptEnum.Equal, V = clsId };
            }
            if (!string.IsNullOrEmpty(corpName))
            {
                queryCompanyInfoCondition.CorpName = new ParameterValue<string>() { O = OptEnum.Like, V = corpName };
            }
            if (!string.IsNullOrEmpty(hdGid.Value))
            {
                Guid corpuserGuid = Guid.Empty;
                if(Guid.TryParse(hdEntityGuid.Value,out corpuserGuid))
                {             
                queryCompanyInfoCondition.CorpUserGuid = new ParameterValue<Guid> { O = OptEnum.Equal, V = corpuserGuid };
                }
            }
            ////解决烟台地区查看外地企业需求,这里说是地区号换字段了，但是前台获取不到变更后的字段，暂时还取以前的账号 2014-01-02 毛凯
            if (UserInfo.AreaCode.Length >= 4)
            {
                queryCompanyInfoCondition.AreaCode = new ParameterValue<string>() { O = OptEnum.StartWith, V = UserInfo.AreaCode };
            }
            queryCompanyInfoList.Add(queryCompanyInfoCondition);
            return JsonConvert.SerializeObject(queryCompanyInfoList);
        }

        public override bool IsCheckPermission
        {
            get { return false; }
        }
    }
}